package com.zmhz.intercept;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.eova.aop.AopContext;
import com.eova.aop.MetaObjectIntercept;
import com.eova.common.utils.EncryptUtil;
import com.eova.common.utils.xx;
import com.eova.core.meta.MetaDataType;
import com.eova.model.MetaField;
import com.jfinal.ext.kit.DateKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class FrontuserIntercept extends MetaObjectIntercept {
	private String token = null;
	private Integer userstatus = 0;
	private Integer usertype = 0;
	/**
	 * 用户注册时密码加密储存、生成token、注册时间、登录时间
	 * 
	 */
	@Override
	public String addBefore(AopContext ac) throws Exception {

		// 新增时密码加密储存
		String str = ac.record.getStr("pwd");
		String str2 = ac.record.getStr("phone");
		String sql = "select count(*) from frontusers where phone = ?";
		//Db.use(ac.object.getDs()).queryInt(sql, str2);
		int count = Db.queryInt(sql, str2);
		if(count>0) {
			return "该手机号"+str2+"已注册，请更换其它手机号，或联系客服！";
		}
		ac.record.set("pwd", EncryptUtil.getSM32(str));
		token = EncryptUtil.getSM32(str2);
		ac.record.set("token", token);
		String now = DateKit.toStr(new Date(), DateKit.timeStampPattern);
		ac.record.set("regtime", now);//注册时间
		ac.record.set("lasttime", now);//上次登录时间
		ac.record.set("logintime", now);//本次登录时间
		ac.record.set("userstatus", userstatus);//用户状态：注册用户
		ac.record.set("errornum", 0);//登录
		return null;
	}
	/**
	 * 将注册用户的信息放入record中
	 */
	@Override
	public String addAfter(AopContext ac) throws Exception {
		
		String user = JsonKit.toJson(getMap());
		ac.record.set("zmhzpt_user", user);
		return null;
	}
	
	/**
	 * 按token值更新用户信息时先查询出id的值,放入record中
	 */
	@Override
	public String updateBefore(AopContext ac) throws Exception {
		Integer id = ac.record.getInt("id");
		String phone = ac.record.getStr("phone");
		if(xx.isEmpty(id)) {
			token  = ac.record.getStr("token");
			String sql = "select id from frontusers where token = ?";
			id = Db.use(ac.object.getDs()).queryInt(sql, token);
			
			sql = "select count(*) from frontusers where phone = ? and id !=";
			int count = Db.use(ac.object.getDs()).queryInt(sql, phone,id);
			if(count>0) {
				return "该手机号"+phone+"已注册，请更换其它手机号，或联系客服！";
			}
			ac.record.set("id", id);
		}
		return null;
	}
	@Override
	public String updateAfter(AopContext ac) throws Exception {
		
		return null;
	}
	
	
	public Map<String,Object> getMap(){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("token", token);
		map.put("userstatus", userstatus);
		map.put("usertype", usertype);
		return map;
	}
	
	
}
